'use strict';
const Sequelize = require('sequelize');

const DbProvider = require('../db/db_provider');

const CATE_STORE = Symbol('CATEGORY#STORE');
const CATE_GET_ALL = Symbol('CATEGORY#GET#ALL');

class RCMSCategoriesStore {
  constructor() {
    this.db = DbProvider.getOldDb();
  }

  async fetch() {
    if (!this[CATE_STORE]) {
      this[CATE_STORE] = await this[CATE_GET_ALL]();
    }
    return this[CATE_STORE] || [];
  }

  list() {
    return this.fetch();
  }

  /**
   * 根据id获取数据
   * @param {Number} id catid
   * @return {Object} 栏目实体
   */
  async getById(id) {
    const list = await this.list();
    return list.find(m => m.id === id);
  }
  /**
   * 获取栏目的全路径
   * @param {Object} current 栏目
   * @return {String} 栏目的全路径（对应新系统的栏目level_code）
   */
  async getFullPath(current) {
    return this.recursiveGetPath(current, current.name);
  }

  async recursiveGetPath(cate, result) {
    if (cate.parentid) {
      const parent = await this.list.find(m => m.id === cate.parentid);
      if (parent) {
        result = `${parent.name}-${result}`;
        return this.recursiveGetPath(parent, result);
      }
    }
    return result;
  }

  /**
   * 查询所有的rcms_Categories
   * @return {Promise<Array>} 数据行
   */
  [CATE_GET_ALL]() {
    return this.db.query(
      'SELECT id,siteid as siteId, rtrim(ltrim(name)) name, parentid,path,filter,cattype, status from rcms_Categories where siteid = 34 order by status desc',
      {
        raw: true,
        type: Sequelize.QueryTypes.SELECT,
      },
    );
  }
}

module.exports = new RCMSCategoriesStore();
